package cn.net.zidian.mvvm.activity;

import android.view.LayoutInflater;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import java.util.ArrayList;
import java.util.List;

import cn.net.zidian.R;
import cn.net.zidian.databinding.ActivityHomeBinding;
import cn.net.zidian.mvvm.fragment.DaiBanFragment;
import cn.net.zidian.mvvm.fragment.HomeFragment;
import cn.net.zidian.mvvm.fragment.MineFragment;
import cn.net.zidian.mvvm.vm.BaseViewModel;

/**
 * 主页
 */
public class HomeActivity extends BaseActivity {

    private ActivityHomeBinding viewBinding;

    private List<Fragment> fragmentList = new ArrayList<>();

    private int position = 0;

    @Override
    protected BaseViewModel viewModel() {
        return null;
    }

    @Override
    protected void initView() {
        viewBinding = ActivityHomeBinding.inflate(LayoutInflater.from(this));
        setContentView(viewBinding.getRoot());
        fragmentList.add(new HomeFragment());
        fragmentList.add(new DaiBanFragment());
        fragmentList.add(new MineFragment());

        viewBinding.llHome.setOnClickListener(view -> {
            if (position != 0) {
                showFragment(0);
            }
        });

        viewBinding.llDaiban.setOnClickListener(view -> {
            if (position != 1) {
                showFragment(1);
            }
        });


        viewBinding.llMine.setOnClickListener(view -> {
            if (position != 2) {
                showFragment(2);
            }
        });

        showFragment(0);
    }

    private void showFragment(int position) {
        this.position = position;
        FragmentTransaction tran = getSupportFragmentManager().beginTransaction();
        Fragment fragment = fragmentList.get(position);
        for (Fragment f : fragmentList) {
            if (f.isAdded()) {
                tran.hide(f);
            }
        }
        if (!fragment.isAdded()) {
            tran.add(R.id.fragment_content, fragment);
        }
        tran.show(fragment);
        tran.commitAllowingStateLoss();
    }
}
